# from fastapi.exceptions import HTTPException
from starlette.exceptions import HTTPException
# 官方推荐注册异常处理器时，应该注册到
# 来自 Starlette 的 HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi import status

# 全局异常
async def global_http_exception_handler(request, exc):
    """全局HTTP异常处理函数"""
    print(exc,type(exc),dir(exc))
    if exc.status_code == 500:
        err_msg = 'Server Internal Error'
    else:
        err_msg = exc.detail

    return JSONResponse({
        'code': exc.status_code,
        'err_msg': err_msg,
        'status': 'Failed'
    })

# 请求数据无效时的错误处理
""" 
example: http://127.0.0.1/user/{user_id}
success: http://127.0.0.1/user/1
failed: http://127.0.0.1/user/d
"""
async def global_validation_exception_handler(request,exc):
    """全局校验异常处理函数"""
    return JSONResponse({
        'code':status.HTTP_422_UNPROCESSABLE_ENTITY,
        'err_msg':exc.errors()[0],
        'status':'Failed'
    })